package org.chench.test.helloserviceclient.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.loadbalancer.RandomRule;
import com.netflix.loadbalancer.RoundRobinRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class HelloClientService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    // 使用注解对方法创建断路器功能
    @HystrixCommand(fallbackMethod = "helloError")
    public String sayHello(String name) {
        //ServiceInstance serviceInstance = this.loadBalancerClient.choose("hello-service"); // 选择指定客户端的负载均衡策略
        //System.out.println("当前选择的服务实例是，host: " + serviceInstance.getHost() + ", port: " + serviceInstance.getPort() + ", service id: " + serviceInstance.getServiceId());

        String url = new StringBuilder().append("http://HELLO-SERVICE/hello/").append(name).toString();
        return restTemplate.getForObject(url, String.class);
    }

    public String helloError(String name) {
        return new StringBuilder().append("Hello, ").append(name).append(", Sorry! ERROR At ").append(this.getClass().getName()).toString();
    }

//    RandomRule
//    RoundRobinRule


}
